package cn.bdqn.fragment02;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button btnHandover;
    private Fragment fragment;
    private OneFragment oneFragment;
    private TwoFragment twoFragment;

    //动态加载Fragment
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //管理器
        FragmentManager fragmentManager = getSupportFragmentManager();
        //开启事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        oneFragment = new OneFragment();
        fragment=oneFragment;
        fragmentTransaction.add(R.id.fl, fragment);
        fragmentTransaction.commit();

        btnHandover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fragmentManager1 = getSupportFragmentManager();//获取管理器
                FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
                twoFragment = new TwoFragment();
                if (fragment instanceof OneFragment) {
                    fragment = twoFragment;
                } else {
                    fragment = oneFragment;
                }

                fragmentTransaction1.replace(R.id.fl, twoFragment);
                fragmentTransaction1.commit();
            }
        });
    }
}
